/**
 * 
 */
package com.zyj.blog.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zyj.blog.common.SysConstants;
import com.zyj.blog.http.HttpResult;
import com.zyj.blog.page.PageRequest;
import com.zyj.blog.pojo.SysUser;
import com.zyj.blog.service.SysUserService;
import com.zyj.blog.util.PasswordUtils;

/**
 * @author zyj
 *
 */
@RestController
@RequestMapping("/user")
public class SysUserController {
	
	@Autowired
	private SysUserService sysUserService;
	
	@GetMapping("/findPermissions")
	public HttpResult findPermissions (@RequestParam String username) {
		return HttpResult.ok(sysUserService.findPermissions(username));
	}
	
	@PostMapping(value="/findPage")
	public HttpResult findPage(@RequestBody PageRequest pageRequest) {
		return HttpResult.ok(sysUserService.findPage(pageRequest));
	}
	
	@PostMapping(value="/save")
	public HttpResult save(@RequestBody SysUser sysUser) {
		SysUser user = sysUserService.findById(sysUser.getId());
		if(user != null) {
			if(SysConstants.ADMIN.equalsIgnoreCase(user.getName())) {
				return HttpResult.error("超级管理员不允许修改!");
			}
		}
		if(sysUser.getPassword() != null) {
			String salt = PasswordUtils.getSalt();
			if(user == null) {
				// 新增用户
				if(sysUserService.findByUserName(sysUser.getName()) != null) {
					return HttpResult.error("用户名已存在!");
				}
				String password = PasswordUtils.encrypte(sysUser.getPassword(), salt);
				sysUser.setSalt(salt);
				sysUser.setPassword(password);
			} else {
				// 修改用户, 且修改了密码
				if(!sysUser.getPassword().equals(user.getPassword())) {
					String password = PasswordUtils.encrypte(sysUser.getPassword(), salt);
					sysUser.setSalt(salt);
					sysUser.setPassword(password);
				}
			}
		}
		return HttpResult.ok(sysUserService.save(sysUser));
	}
	
	@PostMapping(value="/delete")
	public HttpResult delete(@RequestBody List<SysUser> records) {
		for(SysUser record:records) {
			SysUser sysUser = sysUserService.findById(record.getId());
			if(sysUser != null && SysConstants.ADMIN.equalsIgnoreCase(sysUser.getName())) {
				return HttpResult.error("超级管理员不允许删除!");
			}
		}
		return HttpResult.ok(sysUserService.delete(records));
	}
} 
